package cbfg.http.demo.gank

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import cbfg.http.demo.gank.entity.SubCategory

/**
 * @author:  Tom Hawk
 * 添加时间: 2020/9/22 11:29
 * 功能描述:
 */
class SubCategoryAdapter(context: Context) : BaseAdapter() {
    private val layoutInflater = LayoutInflater.from(context)
    private var items = ArrayList<SubCategory>()

    fun setItems(items: List<SubCategory>?) {
        this.items.clear()
        if (items != null) {
            this.items.addAll(items)
        }
        notifyDataSetChanged()
    }

    override fun getItem(position: Int) = items[position]
    override fun getItemId(position: Int) = position.toLong()
    override fun getCount() = items.size

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val vh: ViewHolder = if (convertView != null) {
            convertView.tag as ViewHolder
        } else {
            val view = layoutInflater.inflate(android.R.layout.simple_list_item_1, parent, false)
            ViewHolder(view).also { view.tag = it }
        }
        vh.setContent(getItem(position))
        return vh.itemView
    }

    private class ViewHolder(val itemView: View) {
        private val text1 = itemView.findViewById<TextView>(android.R.id.text1)
        fun setContent(category: SubCategory) {
            text1.text = category.title
        }
    }
}